package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.SysUser;
import service.SysUserService;
import utils.Constants;

import jakarta.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Resource(name = "sysUserService")
    private SysUserService userService;


    @GetMapping("/user/toUpdatePwd")
    public String toUpdatePwd() {
        System.out.println("跳转修改密码页面");
        return "sysUser/updatePassword";
    }

    @PostMapping("/user/savePassword")
    public String savePassword(@RequestParam("id") Integer id, @RequestParam("newPassword") String newPassword, HttpServletRequest request) {
        System.out.println("修改密码提交： id"+id + " newPassword：" + newPassword+"     |");
        SysUser user=new SysUser();
        user.setId(id);
        user.setPassword(newPassword);
        boolean update = userService.update(user);
        if(!update){
            request.setAttribute("message","修改密码失败");
            return "sysUser/updatePassword";
        }
        return "redirect:/login";
    }

    @ResponseBody
    @PostMapping("/user/checkOldPwd")
    public Object checkOldPwd(@RequestParam("oldPassword") String oldPassword, HttpSession session) {
        Map<String,String> result=new HashMap<>();
        result.put("result","true");
        SysUser user = (SysUser) session.getAttribute(Constants.USER_SESSION);
        System.out.println("检查旧密码： oldPassword"+ oldPassword+"|");
        if(oldPassword==null || oldPassword.equals("")){
            result.put("result","error");
        }

        if (user == null){
            result.put("result","sessionerror");
        }else if(!user.getPassword().equals(oldPassword)){
            result.put("result","false");
        }
        System.out.println("result:"+result);
        return result;
    }
}
